package com.android.lovely.ui.activity

import android.animation.ValueAnimator
import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.ViewGroup.MarginLayoutParams
import androidx.activity.addCallback
import androidx.activity.viewModels
import androidx.core.animation.doOnEnd
import androidx.core.view.marginBottom
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.android.lovely.R
import com.android.lovely.api.service.userService
import com.android.lovely.const.CreatedRoleRefresh
import com.android.lovely.const.FinishCreateRole
import com.android.lovely.databinding.ActivityCreateRoleBinding
import com.android.lovely.framework.BaseActivity
import com.android.lovely.room.role.CacheRoleServer
import com.android.lovely.room.role.CacheRoleServer.observeRole
import com.android.lovely.room.role.CreateRoleDataBase
import com.android.lovely.ui.dialog.showLovelyDialog
import com.android.lovely.ui.fragment.role.CreateRoleBaseFragment
import com.android.lovely.ui.fragment.role.CreateRoleStep1Fragment
import com.android.lovely.ui.fragment.role.CreateRoleStep2Fragment
import com.android.lovely.ui.fragment.role.CreateRoleStep3Fragment
import com.android.lovely.ui.fragment.role.CreateRoleStep4Fragment
import com.android.lovely.ui.fragment.role.CreateRoleStep5Fragment
import com.android.lovely.ui.viewmodel.CreateRoleViewModel
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.bus.post
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.keyboard.KeyboardManager
import com.kotlin.extensions.keyboard.hideKeyboard
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

/**
 *
 * @author why
 * @date 2025/4/5 16:17
 */
class CreateRoleActivity : BaseActivity<ActivityCreateRoleBinding>() {

    val viewModel by viewModels<CreateRoleViewModel>()

    private val keyboardManager: KeyboardManager by lazy { KeyboardManager(this) }


    override fun initView(savedInstanceState: Bundle?) {
       mBinding.flTop.addStatusBarMarginTop()
        viewModel.getSmartPrice()
        mBinding.clRoot.clickable {
            hideKeyboard()
        }
        mBinding.back.clickable {
            onBackPressedDispatcher.onBackPressed()
        }
        mBinding.ivDelete.clickable {
            delete()
        }
        onBackPressedDispatcher.addCallback(this@CreateRoleActivity){
            if (viewModel.isQuick) {
                finish()
            } else {
                onBackWarning()
            }
        }
        val id = intent.getIntExtra("role_id", SystemClock.elapsedRealtime().toInt())
        val isEdit = intent?.getBooleanExtra("edit_model", false) ?: false
        val isQuick = intent?.getBooleanExtra("is_quick", false) ?: false
        val index = intent?.getIntExtra("index", 0) ?: 0
        viewModel.isEdit = isEdit
        viewModel.isQuick = isQuick
        mBinding.cdw1.init(1)
        mBinding.cdw2.init(2)
        mBinding.cdw3.init(3)
        mBinding.cdw4.init(4)
        mBinding.cdw5.init(5)

        mBinding.vp2.isUserInputEnabled = false
        mBinding.vp2.adapter = FragmentAdapter()
//        mBinding.vp2.offscreenPageLimit = 5
        mBinding.vp2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                selectPosition(position)
            }
        })
        mBinding.vp2.currentItem = index
        keyboardManager.setOnKeyboardStateListener {
            onProgress {
                val currentPosition = mBinding.vp2.currentItem
                val fragment = supportFragmentManager.findFragmentByTag("f$currentPosition")
                if (fragment is CreateRoleBaseFragment<*>) {
                    // 在这里添加你需要执行的逻辑
                    fragment.onKeyBoardChange(it)
                }
            }
        }

        lifecycleScope.launchSafety{
            viewModel.stepFlow.collect {
                hideKeyboard()
                mBinding.vp2.currentItem = it
            }
        }
        lifecycleScope.launchSafety{
            viewModel.createRoleFlow.collectLatest {
                Log.d("CreateRoleActivity", "collectLatest: ${it}")
            }
        }
        lifecycleScope.observeRole(id) {
            mBinding.vp2.post {
                viewModel.initRole(id,isEdit, it)
            }
        }
        FlowBus.flowOf<FinishCreateRole>().onEach { finish() }.launchIn(lifecycleScope)

    }

    private fun delete() {
        showLovelyDialog {
            setDialogTitle(getString(R.string.delete_role))
            setPositiveButton (getString(R.string.btn_continue)) {
                lifecycleScope.launchSafety {
                    val remoteId = viewModel.id
                    if (remoteId > 0) {
                        runCatching {
                            userService.deleteRole(mapOf("draft_id_list" to remoteId.toString()))
                            FlowBus.post(CreatedRoleRefresh())
                        }
                    }
                    FlowBus.post(FinishCreateRole())
                    CacheRoleServer.remove(viewModel.id)
                    CreateRoleDataBase.dao.delete(viewModel.id)
                    finish()
                }
            }
            setNegativeButton (getString(R.string.quit)) {

            }
        }
    }

    private fun onBackWarning() {
        showLovelyDialog {
            setDialogTitle(getString(R.string.create_role_back, "${ maxOf(1, 6 - mBinding.vp2.currentItem)}"))
            setNegativeButton(getString(R.string.quit)) {
                dismiss()
            }
            setPositiveButton(getString(R.string.btn_continue)) {
                supportFragmentManager.fragments.forEach {
                    if (it is CreateRoleBaseFragment<*>) {
                        it.save()
                    }
                }
                viewModel.save()
                finish()
            }

        }
    }

    fun selectPosition(position: Int) {
        when (position) {
            0 -> {
                mBinding.cdw1.showChecked()
                mBinding.cdw2.showUnChecked()
                mBinding.cdw3.showUnChecked()
                mBinding.cdw4.showUnChecked()
                mBinding.cdw5.showUnChecked()
            }

            1 -> {
                mBinding.cdw1.showDone()
                mBinding.cdw2.showChecked()
                mBinding.cdw3.showUnChecked()
                mBinding.cdw4.showUnChecked()
                mBinding.cdw5.showUnChecked()
            }

            2 -> {
                mBinding.cdw1.showDone()
                mBinding.cdw2.showDone()
                mBinding.cdw3.showChecked()
                mBinding.cdw4.showUnChecked()
                mBinding.cdw5.showUnChecked()
            }

            3 -> {
                mBinding.cdw1.showDone()
                mBinding.cdw2.showDone()
                mBinding.cdw3.showDone()
                mBinding.cdw4.showChecked()
                mBinding.cdw5.showUnChecked()
            }

            4 -> {
                mBinding.cdw1.showDone()
                mBinding.cdw2.showDone()
                mBinding.cdw3.showDone()
                mBinding.cdw4.showDone()
                mBinding.cdw5.showChecked()
            }
        }
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (!hasFocus && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val currentPosition = mBinding.vp2.currentItem
            val fragment = supportFragmentManager.findFragmentByTag("f$currentPosition")
            if (fragment is CreateRoleBaseFragment<*>) {
                // 在这里添加你需要执行的逻辑
                fragment.onKeyBoardChange(0)
            }
        }
    }

    private inner class FragmentAdapter : FragmentStateAdapter(this) {

        override fun getItemCount(): Int {
            return 5
        }

        override fun createFragment(position: Int): Fragment {
            return when (position) {
                0 -> CreateRoleStep1Fragment()
                1 -> CreateRoleStep2Fragment()
                2 -> CreateRoleStep3Fragment()
                3 -> CreateRoleStep4Fragment()
                4 -> CreateRoleStep5Fragment()
                else -> CreateRoleStep1Fragment()
            }
        }
    }

    companion object {
        fun startEdit(activity: Activity, index: Int, createId: Int, edit: Boolean = true, quick: Boolean = false) {
            activity.startPage<CreateRoleActivity>(
                "index" to index,
                "edit_model" to edit,
                "role_id" to createId,
                "is_quick" to quick)
        }
    }
}